<html>
	<body>
		
		<form method="get">
		<font size=5>Type an SQL query in the following box:</font><br>
		<textarea rows="5" cols="60" wrap="soft" name="query"><?php echo $_GET["query"]?></textarea>
		<input type="submit" value="Submit" />
		</form>
		
		<?php
			// connect to sever
			$connection = mysql_connect("localhost", "cs143", "");
			if (!$connection) {
   				 die('Could not connect: ' . mysql_error());
			}
			// connect to database
			$database = mysql_select_db('CS143', $connection);
			if (!$database) {
  			  	die ('Cannot connect to database: ' . mysql_error());
			}
			// do query only if user submitted one
			if($_GET["query"] != NULL) {
				// never trust user input
				$sanitized_query = mysql_real_escape_string($_GET["query"]);
				$result = mysql_query($sanitized_query);
				// make the table look all nice
				echo "<TABLE borderColor=#000000 cellSpacing=0 cellPadding=6 border=2>\n";
       			echo "<TBODY>\n";
       			echo "<TR vAlign=top bgColor=#00ffff>\n";
       			// fill up the table
       			$i = 0;
       			while ($i < mysql_num_fields($result)) { 
               		echo "<TH>". mysql_field_name($result, $i) . "</TH>\n"; 
                	$i++; 
            	} 
       			echo "</TR>\n";
       			
       			while($row = mysql_fetch_assoc($result)) {
  					echo "<TR>\n"; 
                	foreach ($row as $data) { 
                		if($data == NULL) {
                			$data = "N/A";
                		}
                   		echo "<TD align='center'>". $data . "</TD>\n"; 
                   	} 
                	echo "</TR>\n";
  				}
       			echo "</TBODY>\n</TABLE>\n";
  			}
			mysql_close($connection);
			
		?>
	
	</body>
</html>
